package com.maochd.cloud.excel.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.maochd.cloud.common.core.constant.CommonConstant;
import com.maochd.cloud.excel.convert.LocalDateTimeConverter;
import com.maochd.cloud.excel.handler.ColumnWidthHandler;
import com.maochd.cloud.excel.handler.CustomCellWriteHandler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ExcelUtils {

    public static <T> List<T> readExcel(InputStream in, Class<T> clazz) {
        return EasyExcel.read(in).head(clazz).sheet().doReadSync();
    }

    public static ByteArrayInputStream generateFailExcel(List<?> failDataList, ByteArrayOutputStream os, Class<?> clazz) {
        Set<String> includeSet = SpringUtils.listAllField(clazz).stream().filter(f -> f.isAnnotationPresent(ExcelProperty.class)).
                map(Field::getName).collect(Collectors.toSet());
        EasyExcel.write(os, clazz).sheet()
                .registerConverter(new LocalDateTimeConverter())
                .registerWriteHandler(StyleUtils.globalWriteHandler())
                .registerWriteHandler(new ColumnWidthHandler())
                .registerWriteHandler(new CustomCellWriteHandler())
                .includeColumnFiledNames(includeSet)
                .doWrite(failDataList);
        return new ByteArrayInputStream(os.toByteArray());
    }

    public static String fileName(LocalDateTime createTime, String sn) {
        return sn + createTime.format(CommonConstant.DTF) + ExcelTypeEnum.XLSX.getValue();
    }

    public static boolean isIntegerValue(BigDecimal bd) {
        return bd.remainder(new BigDecimal("1")).compareTo(BigDecimal.ZERO) == 0;
    }

    /**
     * 生成上传文件名
     *
     * @param folder   文件夹名
     * @param filename 文件名
     * @return 上传文件名
     */
    public static String generateUploadFilename(String folder, String filename) {
        return StrUtil.isBlank(filename) ? StrUtil.EMPTY : String.format(folder, filename);
    }

}
